/*
 * Copyright (C) 2018 Logos Technology Ltd.
 */

package com.logos.common.update;

import org.json.JSONException;
import org.json.JSONObject;

public class UpdateInfo {
    // 是否有新版本
    public boolean hasUpdate = false;
    // 是否静默下载：有新版本时不提示直接下载
    public boolean isSilent = false;
    // 是否强制安装：不安装无法使用app
    public boolean isForce = false;
    // 是否下载完成后自动安装
    public boolean isAutoInstall = true;
    // 是否可忽略该版本
    public boolean isIgnorable = true;
    // 一天内最大提示次数，<1时不限
    public int maxTimes = 0;

    public int versionCode;
    public String versionName;

    public String updateContent;

    public String url;
    public String md5;
    public long size;

    /**
     * 解析
     * @param string string
     * @return UpdateInfo
     * @throws JSONException If an exception is thrown out of an exception
     */
    public static UpdateInfo parse(String string) throws JSONException {
        JSONObject object = new JSONObject(string);
        return parse(object.has("data") ? object.getJSONObject("data") : object);
    }

    private static UpdateInfo parse(JSONObject object) {
        UpdateInfo info = new UpdateInfo();
        if (object == null) {
            return info;
        }
        info.hasUpdate = object.optBoolean("hasUpdate", false);
        if (!info.hasUpdate) {
            return info;
        }
        info.isSilent = object.optBoolean("isSilent", false);
        info.isForce = object.optBoolean("isForce", false);
        info.isAutoInstall = object.optBoolean("isAutoInstall", !info.isSilent);
        info.isIgnorable = object.optBoolean("isIgnorable", true);

        info.versionCode = object.optInt("versionCode", 0);
        info.versionName = object.optString("versionName");
        info.updateContent = object.optString("updateContent");

        info.url = object.optString("url");
        info.md5 = object.optString("md5");
        info.size = object.optLong("size", 0);

        return info;
    }
}
